#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "myc.h"

char *instr;

void prtokoff(struct token *tok) {
	if (!instr) return;
	int line=1,ch=1;
	char *in=instr;
	while (in<tok->str) {
		if (*in=='\n') {
			line++;
			ch=1;
		} else ch++;
		in++;
	}
	printf("%d:%d: ",line,ch);
}

int main (int argc,char **argv) {
	int c;
	char *infile=NULL,*outfile=NULL;
	while ((c=getopt(argc,argv,"-:o:"))!=-1) switch(c) {
	case 'o':
		if (outfile) error("only one outfile");
		outfile=optarg;
		break;
	case 1:
		if (infile) error("only one infile");
		infile=optarg;
		break;
	default: error("invalid option");
	}
	if (!outfile) outfile="output.asm";
	if (!infile) error("no infile");
	output=fopen(outfile,"w");
	if (!output) error("cannot create file");
	int fd = open (infile, O_RDONLY);
	if(fd==-1) error("cannot open file");
	int nbytes = lseek(fd, 0, SEEK_END);
	instr = mmap(NULL, nbytes, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
	struct token *tok=splitoken(instr,instr+nbytes);
	init();
	pass=tok;
	run_file();
	freetokens(tok);
	cleanup();
	return 0;
}
